package io.kiki.stack.netty.processor;

import io.kiki.stack.netty.channelManager.ChannelContext;
import io.kiki.stack.netty.command.AbstractRequestCommand;
import io.kiki.stack.netty.util.InetSocketAddressUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Setter
@Getter
public class RequestProcessTask implements Runnable {

    private final RequestProcessor requestProcessor;
    ChannelContext channelContext;
    AbstractRequestCommand requestCommand;

    public RequestProcessTask(RequestProcessor requestProcessor, ChannelContext channelContext, AbstractRequestCommand requestCommand) {
        this.requestProcessor = requestProcessor;
        this.channelContext = channelContext;
        this.requestCommand = requestCommand;
    }


    @Override
    public void run() {
        try {
            requestProcessor.doProcess(channelContext, requestCommand);
        } catch (Throwable e) {
            //protect the thread running this task
            String remotingAddress = InetSocketAddressUtil.parseRemoteAddress(channelContext.getChannelHandlerContext().channel());
            String errMsg = "Exception caught when process rpc request command in RpcRequestProcessor, Id=" + requestCommand.getId();
            log.error(errMsg + "! Invoke source address is [" + remotingAddress + "].", e);
            requestProcessor.sendResponseIfNecessary(channelContext, requestCommand.getType(), requestProcessor.getCommandFactory().createExceptionResponse(requestCommand.getId(), errMsg, e));
        }
    }

}
